from psycopg2 import pool
import logging
import configparser
import os
# 配置日志记录
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

class Database:
    __connection_pool = None

    @staticmethod
    def initialize(config_file='config/config.ini'):
        config = configparser.ConfigParser()
        config.read(config_file)
        db_config = config['database']

        try:
            Database.__connection_pool = pool.SimpleConnectionPool(
                1,
                int(db_config['max_connections']),
                host=db_config['host'],
                database=db_config['database'],
                user=db_config['user'],
                password=db_config['password'],
                port=int(db_config['port']),
                connect_timeout=int(db_config['connection_timeout'])
            )
            logging.info("Database connection pool initialized successfully.")
        except Exception as e:
            logging.error(f"Failed to initialize database connection pool: {e}")
            raise

    @staticmethod
    def get_connection():
        if Database.__connection_pool is None:
            raise Exception("Database connection pool is not initialized. Call initialize() first.")
        try:
            conn = Database.__connection_pool.getconn()
            logging.debug("Connection retrieved from pool.")
            return conn
        except Exception as e:
            logging.error(f"Failed to get connection from pool: {e}")
            raise

    @staticmethod
    def return_connection(conn):
        if Database.__connection_pool is None:
            raise Exception("Database connection pool is not initialized. Call initialize() first.")
        try:
            Database.__connection_pool.putconn(conn)
            logging.debug("Connection returned to pool.")
        except Exception as e:
            logging.error(f"Failed to return connection to pool: {e}")
            raise

    @staticmethod
    def close_all_connections():
        if Database.__connection_pool is not None:
            try:
                Database.__connection_pool.closeall()
                logging.info("All database connections closed.")
            except Exception as e:
                logging.error(f"Failed to close all database connections: {e}")
            finally:
                Database.__connection_pool = None

# 上下文管理器类
class DatabaseConnection:
    def __init__(self):
        self.conn = None
        self.cursor = None
        self.commit_on_exit = False

    def __enter__(self):
        try:
            self.conn = Database.get_connection()
            self.cursor = self.conn.cursor()
            logging.debug("Cursor created.")
            return self.cursor
        except Exception as e:
            logging.error(f"Failed to create cursor: {e}")
            raise

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.cursor:
            try:
                self.cursor.close()
                logging.debug("Cursor closed.")
            except Exception as e:
                logging.error(f"Failed to close cursor: {e}")
        if self.conn:
            try:
                if self.commit_on_exit and not exc_type:
                    self.conn.commit()
                    logging.debug("Transaction committed in DatabaseConnection.")
                else:
                    self.conn.rollback()
                    logging.debug("Transaction rolled back in DatabaseConnection.")
                Database.return_connection(self.conn)
                logging.debug("Connection returned to pool.")
            except Exception as e:
                logging.error(f"Failed to return connection to pool: {e}")
        if exc_type:
            logging.error(f"Exception occurred: {exc_val}")
            raise

    def set_commit_on_exit(self, commit_on_exit):
        self.commit_on_exit = commit_on_exit